package com.leyou.common.interceptor;


import com.leyou.common.auth.domain.UserHolder;
import com.leyou.common.uploadimgs.LyConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 当前拦截器就是预先获取到当前请求中的用户id，然后将其存储到一个容器中
 */
@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String userIdStr = request.getHeader(LyConstants.USER_ID_KEY);
        if(StringUtils.isBlank(userIdStr)){
            log.info("【拦截器获取用id】失败!当前用户未认证！");
            return true;
        }
        Long userId = Long.valueOf(userIdStr);
        //将用户id存入到自定义对象中
        UserHolder.setUserId(userId);
        return true;
    }
}